/*
 * Introspection.java
 *
 * Created on April 5, 2007, 11:26 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.app;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.SQLException;
import java.util.logging.Level;
import org.atomojo.app.db.DB;
import org.atomojo.app.db.Feed;
import org.infoset.xml.util.WriterItemDestination;
import org.restlet.Application;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.representation.OutputRepresentation;
import org.restlet.representation.Representation;

/**
 *
 * @author alex
 */
public class Introspection extends Restlet
{
   public static final MediaType ATOM_SERVICE_XML = MediaType.valueOf("application/atomsvc+xml");
   
   Storage storage;
   Reference resourceBase;
   Application app;
   DB db;
   
   /** Creates a new instance of Introspection */
   public Introspection(Application app,DB db,Storage storage,Reference resourceBase)
   {
      this.db = db;
      this.app = app;
      this.storage = storage;
      this.resourceBase = resourceBase;
   }
   
   public void handle(final Request request, Response response)
   {
      if (!request.getMethod().equals(Method.GET)) {
         response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED,"Introspection only responds to get requests.");
         return;
      }
      ;
      String path = request.getResourceRef().getRemainingPart();
      if (path==null) {
         path = request.getResourceRef().getPath();
      }
      int queryPos = path.indexOf('?');
      if (queryPos>=0) {
         path = path.substring(0,queryPos);
      }
      if (path.length()>0 && !path.equals("/")) {
         response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST,"Extended paths (e.g. "+path+") are not supported.");
         return;
      }
      //getContext().getLogger().info("Path: '"+path+"'");
      Representation rep = new OutputRepresentation(Introspection.ATOM_SERVICE_XML) {
         public void write(OutputStream os) {
            try {
               String path = request.getResourceRef().getPath();
               if (path.charAt(path.length()-1)=='/') {
                  path = path.substring(0,path.length()-1);
               }
               Writer w = new OutputStreamWriter(os,"UTF-8");
               db.getIntrospection(
                  storage,
                  request.getResourceRef().toString(),
                  path,
                  new DB.CollectionLocator() {
                     public String makeHref(Feed feed) 
                        throws SQLException
                     {
                        return resourceBase.toString()+feed.getPath();
                     }
                  },
                  new WriterItemDestination(w,"UTF-8")
               );
            } catch (Exception ex) {
               getContext().getLogger().log(Level.SEVERE,"Exception while getting feeds: "+ex.getMessage(),ex);
            }
         }
      };
      rep.setCharacterSet(CharacterSet.UTF_8);
      response.setEntity(rep);
      response.setStatus(Status.SUCCESS_OK);

   }
   
}
